package cn.jiedh.app.meiweidk.network;


import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.alibaba.fastjson.JSON;

import cn.jiedh.app.meiweidk.Utils.UI.AlertDialog;
import cn.jiedh.app.meiweidk.Utils.config.ConfigUtils;
import cn.jiedh.app.meiweidk.Utils.tool.ActivityUtil;
import cn.jiedh.app.meiweidk.Utils.tool.JsonUtil;
import cn.jiedh.app.meiweidk.Utils.tool.L;
import cn.jiedh.app.meiweidk.Utils.tool.NetworkUtils;
import cn.jiedh.app.meiweidk.Utils.tool.SPUtils;
import cn.jiedh.app.meiweidk.Utils.tool.T;
import cn.jiedh.app.meiweidk.login.LoginActivity;
import cn.jiedh.app.meiweidk.response.BaseResponse;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.ex.HttpException;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.Map;


public class AsyncWebServer {
    public static AsyncWebServer mAWs;
    private Context context;
    private static String PUBLIC_KEY = "";//解密加密的公钥
    private static String PRIVATE_KEY = "";//解密加密的私钥

    private AsyncWebServer(Context context) {
        this.context = context;
    }

    public static synchronized AsyncWebServer getInstance(Context context) {
        if (mAWs == null) {
            mAWs = new AsyncWebServer(context.getApplicationContext());
        }
        return mAWs;

    }

    private static final String TAG = "AsyncWebServer";

    //这里是实质发送post请求的地方 这里 查看 每一个请求 发送请求 时带的参数
    private <T> Callback.Cancelable urlPost(final Activity activity, final RequestParams params, final ResponseSuccess success, final ResponseFailure failure) {
        Callback.Cancelable request = null;
        L.d(TAG, "AsyncWebServer：" + params.toString());
        if (NetworkUtils.isConnect(context)) {
            request = x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    //加载成功回调，返回获取到的数据
                    L.e("AsyncWebServer", params.getUri() + " onSuccess: " + result.toString());
                    try {
                        BaseResponse<T> response = JSON.parseObject(result, getResposneType(success));
                        if (response.getCode() == 33) {
                            SPUtils.clearUser(activity);
                            Log.d(TAG, "用户数据清除成功吗：" + SPUtils.clearUser(activity));
                            if (ConfigUtils.isdialogshow) {
                                AlertDialog dialog = new AlertDialog(activity);
                                ConfigUtils.setIsdialogshow(false);
                                dialog.builder().setTitle("提示").
                                        setCanceledOnTouchOutside(true).setMsg("账号在别处登录，您需要重新登录才可以继续使用")
                                        .setNegativeButton("确定", new View.OnClickListener() {
                                            @Override
                                            public void onClick(View view) {
                                                Bundle bundle = new Bundle();
                                                bundle.putBoolean("isGoHome", true);
                                                ActivityUtil.next(activity, LoginActivity.class, bundle);
                                            }
                                        }).setOnDismissListener("33").show();
                            }
                            return;
                        }
                        success.onRequestSucceed(response);
                    } catch (Exception e) {
                        e.printStackTrace();
                        failure.onRequestFailure(null, "服务器错误");
                    }
                }

                @Override
                public void onFinished() {
                    //dia.dismiss();//加载完成
                    L.d("网络请求  onFinished");
                }

                @Override
                public void onCancelled(CancelledException cex) {
                    L.d("网络请求  onCancelled");
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    L.d("网络请求  onError");
                    if (L.isDebug) {
                        ex.printStackTrace();
                    }
                    if (ex instanceof HttpException) { //网络错误
                        HttpException httpEx = (HttpException) ex;
                        String errorResult = httpEx.getResult();
                        L.d(params.getUri() + "   ==>" +   errorResult);


                        cn.jiedh.app.meiweidk.Utils.tool.T.showShort(JsonUtil.getMessage(errorResult).substring(JsonUtil.getMessage(errorResult).indexOf(":")+1));


                        failure.onRequestFailure(null,JsonUtil.getMessage(errorResult).substring(JsonUtil.getMessage(errorResult).indexOf(":")+1));

                    } else { //其他错误
                        //...
                        cn.jiedh.app.meiweidk.Utils.tool.T.showShort("请求失败");
                        failure.onRequestFailure(null, "请求失败");
                    }

                }
            });
        } else {
            cn.jiedh.app.meiweidk.Utils.tool.T.showShort("当前网络不佳，感谢你的耐心等待！");
            failure.onRequestFailure(null, "当前网络不佳，感谢你的耐心等待！");
        }
        return request;
    }

    /**
     * 网络请求
     *
     * @param activity
     * @param url
     * @param map
     * @return
     */
    public Callback.Cancelable request(Activity activity, String url, Map<String, Object> map, boolean isEncry,
                                       ResponseSuccess success, ResponseFailure failure) {
        RequestParams params = new RequestParams(url);
        try {
            mapToParams(map, params);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return urlPost(activity, params, success, failure);
    }

    public void mapToParams(Map<String, Object> map, RequestParams params) {
        params.clearParams();
        L.i("请求参数", "URL = " + params.getUri() + "\n参数" + map.toString());
        JSONObject jsonObject = new JSONObject();
        if (map != null) {
            for (String key : map.keySet()) {
                try {
                    jsonObject.put(key, map.get(key));

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            L.i("请求参数", "URL = " + params.getUri() + "\njson参数" + jsonObject.toString());
            params.addParameter("requestJson", jsonObject);
//默认请求超时时间为10s
            params.setConnectTimeout(15 * 1000);
        }
    }


    /**
     * 埋点统计
     */
//	public void Xtongji(Activity activity, Map<String, Object> map, ResponseSuccess success, ResponseFailure failure) {
//		RequestParams params = new RequestParams("https://api.data.miaoxiakuan.net/v1/report");
//		if (map != null) {
//			for (String key : map.keySet()) {
//				params.addParameter(key, map.get(key));
//			}
//		}
//		urlPost(activity, params, success, failure);
//	}
    private Type getResposneType(ResponseSuccess success) {
        Method[] methods = success.getClass().getMethods();
        for (int i = 0; i < methods.length; i++) {
            if ("onRequestSucceed".equals(methods[i].getName())) {//和传入方法名匹配
//                Class params = methods[i].getParameterTypes()[0];
                Type[] types = methods[i].getGenericParameterTypes();
                return types[0];
            }
        }
        return null;
    }
}
